package com.qitmiaojie.controller;

import com.google.code.kaptcha.Producer;
import com.qitmiaojie.controller.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class LoginController {
    @Autowired
    private Producer producer;
    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 生成验证码
     * @return
     * @throws IOException
     */
    @GetMapping("/verificationCode")
    public Result code() throws IOException {
        String key= UUID.randomUUID().toString();
        //生成验证码
        String text = producer.createText();
        log.info("验证码为 = " + text);
        //将验证码存入redis
        redisTemplate.opsForValue().set(key,text,120, TimeUnit.SECONDS);//过期时间
        BufferedImage image = producer.createImage(text);
        FastByteArrayOutputStream fos = new FastByteArrayOutputStream();
        ImageIO.write(image,"jpg",fos);
        String base64Code = Base64.encodeBase64String(fos.toByteArray());
        String str = "data:image/jpeg;base64,";
        String Base64Image = str+base64Code;
        Result result = new Result();
        Map<String,Object> map=new HashMap<>();
        map.put("key",key);
        map.put("Base64Image",Base64Image);
        result.setStateCode(200);
        result.setObject(map);
        result.setMsg("生成成功");
        return result;
    }
}
